package org.btik.light.mobile.ui.serial.controller;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbDevice;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.widget.Toast;
import org.btik.context.SimpleContext;
import org.btik.light.mobile.R;

import static org.btik.light.mobile.platform.conf.ContextGlobalNames.USB_ATTACH_HOOK;

/**
 * @author lustre
 * @since 2023/4/7 15:28
 */
public class UsbAttachBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        String action = intent.getAction();

        int id = R.string.usb_attached;
        if ("android.hardware.usb.action.USB_DEVICE_DETACHED".equals(action)) {
            id = R.string.usb_detached;
        }
        UsbDevice usbDevice = (UsbDevice) intent.getExtras().get("device");
        USBAttachHook usbAttachHook = SimpleContext.get(USB_ATTACH_HOOK);

        if (usbAttachHook != null) {
           // 播放提示音
            Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            Ringtone r = RingtoneManager.getRingtone(context, notification);
            r.play();

            CharSequence text = context.getResources().getText(id);

            Toast.makeText(context, usbDevice.getProductName() + text, +Toast.LENGTH_SHORT).show();
            //设备不一定是串口设备
            usbAttachHook.refresh();
        }
    }


}
